package com.yhk.wuchat.common.common.service;

import com.yhk.wuchat.common.common.exception.BusinessException;
import com.yhk.wuchat.common.common.exception.CommonErrorEnum;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/4/14 16:05
 * @注释
 */

/**
 * 分布式锁工具类
 */
@Service
public class LockService {
    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取锁，执行业务逻辑
     * @param key
     * @param waitTime
     * @param timeUnit
     * @param supplier
     * @return
     * @param <T>
     */
    @SneakyThrows
    public <T> T executeWithLock(String key, int waitTime, TimeUnit timeUnit, Supplier<T> supplier) {
        RLock lock = redissonClient.getLock(key);
        boolean success = lock.tryLock(waitTime, timeUnit);
        if (!success) {
            throw new BusinessException(CommonErrorEnum.LOCK_LIMIT);
        }
        try{
            //执行·业务逻辑
            return supplier.get();
        }finally {
            lock.unlock();
        }
    }

    @SneakyThrows
    public <T> T executeWithLock(String key, Supplier<T> supplier) {
        return executeWithLock(key,-1,TimeUnit.MINUTES,supplier);
    }

    @SneakyThrows
    public <T> T executeWithLock(String key, Runnable runnable) {
        return executeWithLock(key,-1,TimeUnit.MINUTES,()->{
            runnable.run();
            return null;
        });
    }

    @FunctionalInterface
    public interface Supplier<T> {
        T get() throws Throwable;
    }
}
